﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace StoreApp
{

    public class BookStoreService
    {
        private readonly IStore m_store;

        public BookStoreService()
        {
            m_store = new Store(new PaySystem());
        }
        public BookStoreService(IStore store)
        {
            m_store = store;
        }

        public int GetTotalBooksAmount()
        {
            return m_store.Count();
        }

        public List<string> GetAuthors()
        {
            return m_store.Items.OfType<Book>().ToList().Select(p => p.Author.Trim()).Distinct().ToList();
        }

        public List<string> GetTitles()
        {
            List<string> temp = new List<string>();
   
            foreach (Book book in m_store.Items)
            {
                temp.Add(
                    book.Title.Trim() 
                    + (book.Publisher != string.Empty ? "[" + book.Publisher + "]" : string.Empty) 
                    + (book.ImprintDate != string.Empty ? "["+ book.ImprintDate+"]" : string.Empty)
                    );
            }
            return temp.Distinct().ToList();
        }

        public void AddBook(Book book)
        {
            if (book == null) throw new NullReferenceException("book");
            
            if (book.Author == null || book.Title == null)
                throw new NullReferenceException("book");
            
            m_store.Insert(book);
        }

        public List<Book> FindBooksByAuthors(string author)
        {
            return m_store.Items.OfType<Book>().Where(s => s.Author.Trim().Equals(author.Trim())).ToList();
        }

        public Book FindBooksByTitle(string title)
        {
            return m_store.Items.OfType<Book>().ToList().Find(s => (s.Title.Trim().Equals(title.Trim()))) ?? new NullBook();
        }

        public void Sale(Book book)
        {
            if (book == null) throw new ArgumentNullException("book");
            m_store.Sale(book);
        }
    }
}
